import traceback   
from kafka import KafkaConsumer  # 导入第三方库
import time
import json
import uuid

from pymysql import NULL
from config.SendMail import sendEmail

from config.dbUtils import DBUtil


def readTopic():
    #  与kafka建立连接
    # consumer = KafkaConsumer('car_behavior',group_id='group2',bootstrap_servers=['10.123.46.5:9092'])
    consumer = KafkaConsumer('car_behavior', bootstrap_servers=['127.0.0.1:9092'])
    print("连接成功")
    for message in consumer:  # 开始消费消�?
        # print ("%s %s value=%s" % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),message.topic,message.value))
        message_body = message.value.decode()
        # print ("decode后的数据�? %s " % message_body)
        res = json.loads(message_body)  # 将json字符串转换为python字典形式
        appId = res["app_id"]  # app_ID TBOX上传�?
        if appId in exclodAppId():
            continue
        try:
            saveDb(res)
        except :
            sendEmail(traceback.format_exc())

def saveDb(res):
    dbUtil = DBUtil()
    pid = getUUId()
    currentTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    session_time=NULL
    system_result=NULL 
    app_start = NULL
    if res["event_value"] is not None:
        for jkey in res["event_value"]:
            if jkey == 'system_result':
                system_result = res["event_value"]['system_result']
                continue
            if jkey == 'app_start':
                app_start = res["event_value"]['app_start']
                continue
            if jkey == 'session_time':
                session_time = res["event_value"]['session_time']
                continue
        
    # sql = "INSERT INTO douyin(`id`, `vin`,`type`,`time`,`create_time`) VALUES ('"+pid+"','123','抖音','"+currentTime+"', '"+currentTime+"')"
    sql = "INSERT INTO `car_behavior_info` (`id`,`account_id`,`ai_in_car_id`,`app_id`,`app_name`,`app_version`,`car_brand`,`car_vin`,`device_brand`\
        ,`device_id`,`device_os_name`,`device_os_ver`,`event_code`,`event_time`,`event_type`,`hardware_ver`,`info_str`,`language`,`latitude`,`longitude`\
        ,`mcu_software_ver`,`net_type`,`platform`,`session_time`,`system_result`,`create_time`,`app_start`)\
         VALUES ('"+pid+"','"+res["account_id"]+"','"+res["ai_in_car_id"]+"','"+res["app_id"]+"','"+res["app_name"]+"','"+res["app_version"]+"','"+res["car_brand"]+"','"+res["car_vin"]+"',\
        '"+res["device_brand"]+"','"+res["device_id"]+"','"+res["device_os_name"]+"','"+res["device_os_ver"]+"','"+res["event_code"]+"','"+res["event_time"]+"','"+res["event_type"]+"','"+res["hardware_ver"]+"'\
        ,'"+res["info_str"]+"','"+res["language"]+"','"+res["latitude"]+"','"+res["longitude"]+"','"+res["mcu_software_ver"]+"','"+res["net_type"]+"','"+res["platform"]+"','"+session_time+"'\
        ,'"+system_result+"','"+currentTime+"','"+app_start+"')"
    DBUtil.save(dbUtil, sql)


def getUUId():
    uuidStr = str(uuid.uuid1())
    uuidArr = uuidStr.split("-")
    result = ""
    for i in uuidArr:
        result += i
    return result


def exclodAppId():
    appIdList = ['com.android.launcher', 'gaei.ecallbcall', 'android', 'com.gaei.vehichesetting', 'com.gaei.planet', 'com.gaei.gaeihvsmsettings',
                 'gaei.bluetooth', 'com.ts.app.newenergy', 'gaei.video', 'com.gaei.image', 'com.gaei.settings', 'com.android.systemui', 'com.trumpchi.assistant.app']
    return appIdList


if __name__ == '__main__':
    readTopic()
